package com.heng.test.threadLocal;

import com.alibaba.ttl.TransmittableThreadLocal;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Demo {
    static ThreadLocal<String> threadLocal = new ThreadLocal<>();
    static ThreadLocal<String> inheritableThreadLocal = new InheritableThreadLocal<>();

    static ThreadLocal<String> transmittableThreadLocal = new TransmittableThreadLocal<>();

    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        threadLocal.set("main线程");
        inheritableThreadLocal.set("main线程-inherit");
        new Thread(() -> {
            // threadLocal，子线程获取不到父线程中的值
            System.out.println("子线程：" + threadLocal.get());
            System.out.println("子线程：" + inheritableThreadLocal.get());

            new Thread(() -> { // 也能得到对应的值
                System.out.println("孙线程 " + inheritableThreadLocal.get());
            }).start();
        }).start();

        for (int i = 10; i > 0; i--) {
            inheritableThreadLocal.set(i * 100 + "");
            System.out.println("父线程： "+inheritableThreadLocal.get());
            threadPool.execute(() -> {
                System.out.println("线程池  ---> " + inheritableThreadLocal.get());
            });
        }

    }
}
